package com.psct.music;

import com.psct.Constant;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

/**
 * 背景音乐管理类
 * 
 * @author zjingchuan
 * 
 */
public class MusicManager {
	private static MusicManager mManager;
	// private BgMusicPlayer mPlayer;
	private Context context;
	private MusicService musicService;
	private boolean isBinded = false;
	private ServiceConnection conn = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Log.v("music", "音乐服务绑定成功");
			musicService = ((MusicService.LocalBinder) service).getService();
			musicService.play(mode);
			isBinded = true;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Log.v("music", "音乐服务绑定失败");
		}
	};

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	/**
	 * 播放模式，默认0
	 */
	private int mode = Constant.MODEL_NOMAL;

	private MusicManager() {
	}

	/**
	 * 获得一个实例
	 * 
	 * @return
	 */
	public static MusicManager getInstance() {
		if (mManager == null)
			mManager = new MusicManager();
		return mManager;
	}

	/**
	 * 播放
	 */
	public void play() {
		if (musicService == null) {
			context.bindService(new Intent(context, MusicService.class), conn, Context.BIND_AUTO_CREATE);
		} else {
			musicService.play(mode);
		}
	}

	public int getMode() {
		return mode;
	}

	/**
	 * 设置播放模式
	 * 
	 * @return
	 */
	public void setMode(int mode) {
		if (musicService != null && musicService.isPlay()) {
			stop();
		}
		this.mode = mode;
		play();
	}

	public void stop() {
		if (musicService != null)
			musicService.stopPlayer();

	}
	public void stopService() {
		if(isBinded) {
			context.unbindService(conn);
			musicService=null;
		}
	}
}
